package cmd

import (
	"context"
	"gf-mysql-transfer/internal/storage"
	"github.com/go-mysql-org/go-mysql/mysql"
	"github.com/gogf/gf/v2/frame/g"
	"regexp"
)

type cPositionInput struct {
	g.Meta `name:"position"`
	Name   string `name:"name"            short:"f"`
	Pos    uint32 `name:"pos"            short:"p"`
}
type cPositionOutput struct{}

func (c cServe) Position(ctx context.Context, in cPositionInput) (out *cPositionOutput, err error) {
	err = Initialize(ctx)
	if err != nil {
		panic(err)
	}
	doPosition(ctx, in)
	return nil, nil
}

func doPosition(ctx context.Context, in cPositionInput) {

	if in.Name == "" || in.Pos == 0 {
		g.Log().Error(ctx, "error: please input the binLog's File and Position")
	}

	matched, _ := regexp.MatchString(".+\\.\\d+$", in.Name)
	if !matched {
		g.Log().Error(ctx, "error: The parameter File must be like: mysql-bin.000001")
		return
	}

	ps := storage.NewPositionStorage()
	pos := mysql.Position{
		Name: in.Name,
		Pos:  in.Pos,
	}
	_ = ps.Save(pos)
	g.Log().Infof(ctx, "The current dump position is : %s %d \n", in.Name, in.Pos)
}
